(define-module (email)
  #:use-module (ice-9 popen)
  #:use-module (ice-9 threads)
  #:use-module (srfi srfi-19)
  #:export (send-email))

(define (send-email to subject body)
  (call-with-new-thread
   (lambda ()
     (let ((port (open-pipe* OPEN_WRITE "msmtp" to)))
       (display (email-rfc-2822 subject body) port)
       (close-pipe port)))))

(define (email-rfc-2822 subject body)
  (string-append
   "Subject: " subject "\n"
   "Date: "
   (date->string (current-date) "~a, ~e ~b ~Y ~k:~M:~S ~z")
   "\n"
   "Message-ID: <"
   (number->string (hash (string-append subject body) 1000000000000000000))
   "@"
   (gethostname)
   ">\n\n"
   body))
